﻿using IniFileParser.Model;

namespace Wittur.GenereateKongCoCPDF.Core.Common
{
    public class ConfigHelper
    {
        private static readonly Lazy<ConfigHelper> _instance = new Lazy<ConfigHelper>(() => new ConfigHelper());
        private readonly string _iniFilePath;
        private IniData _cachedData;
        private readonly object _lock = new object();

        public static ConfigHelper Instance => _instance.Value;

        private ConfigHelper()
        {
            _iniFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppConfig.ini");
        }

        public string GetString(string rootPath, string configName)
        {
            try
            {
                if (_cachedData == null)
                {
                    lock (_lock)
                    {
                        if (_cachedData == null)
                        {
                            var parser = new IniFileParser.IniFileParser(); 
                            _cachedData = parser.ReadFile(_iniFilePath);
                        }
                    }
                }

                return _cachedData?[rootPath]?[configName] ?? throw new InvalidOperationException("Connection string not found in config file");
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Failed to read connection string from config file", ex);
            }
        }
    }
}
